﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Moria.Silverlight.Views;
using Moria.Common.Model;
using Moria.Common;
using Moria.Silverlight.Controls;
using Redbrick.Silverlight.Common;

namespace Moria.Silverlight
{
	public partial class MainPage : UserControl
	{
		public MainPage()
		{
			this.DebugMethodInfo();
			InitializeComponent();
			this.Moria.EnterStore += new EventHandler<StoreEventArgs>(Moria_EnterStore);
		}

		void Moria_EnterStore(object sender, StoreEventArgs e)
		{
			this.DebugMethodInfo(sender,e);
			// adjust price for players charisma
			foreach (InventoryRecord rec in e.Store.store_inven)
			{

				int x = rec.BaseCost;
				if (x <= 0)
				{
					int value = -x;
					value = value * Moria.Player.chr_adj / 100;
					if (value <= 0) value = 1;
					rec.AdjustedCost = value;
				}
				else
				{
					rec.AdjustedCost = x;
				}
			}


			StoreDialog sd = new StoreDialog();
			sd.DataContext = e.Store;
			sd.Show();
		}

		// After the Frame navigates, ensure the HyperlinkButton representing the current page is selected
		private void ContentFrame_Navigated(object sender, NavigationEventArgs e)
		{
			this.DebugMethodInfo(sender,e);
			foreach (UIElement child in LinksStackPanel.Children)
			{
				HyperlinkButton hb = child as HyperlinkButton;
				if (hb != null && hb.NavigateUri != null)
				{
					if (hb.NavigateUri.ToString().Equals(e.Uri.ToString()))
					{
						VisualStateManager.GoToState(hb, "ActiveLink", true);
					}
					else
					{
						VisualStateManager.GoToState(hb, "InactiveLink", true);
					}

					if (InventoryView.Uri.OriginalString.StartsWith(hb.NavigateUri.OriginalString) ||
						 MapView.Uri.OriginalString.StartsWith(hb.NavigateUri.OriginalString))
					{
						if (this.Moria.Player == null || string.IsNullOrEmpty(this.Moria.Player.name)) hb.IsEnabled = false;
						else hb.IsEnabled = true;
					}
				}
			}
		}

		protected TheGame Moria { get { return this.DataContext == null ? null : this.DataContext as TheGame; } }

		// If an error occurs during navigation, show an error window
		private void ContentFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
		{
			this.DebugMethodInfo(sender,e);
			e.Handled = true;
			ChildWindow errorWin = new ErrorWindow(e.Uri);
			errorWin.Show();
		}
	}
}